import {
  Form
} from 'antd-mini/es/Form/form';
import {
  timingSafeEqual
} from 'crypto';
import * as api from '/service/service'

Page({
  data: {
    mapV2Enable: dd.canIUse('map.optimize'),
    locationFlag: false,
    longitude: '', // 经度
    latitude: '', // 纬度
    iconAppendStrMarker: [],
    makerId: 1,
    markers: [],

    projectNameValue: null,
    projectNameList: [],
    contractNameList: [],
    contractName: null,
    ioCompany: null,
    responseLevelList: ['常规', '紧急', '特急'],
    faultCategoryList: ['前端', '后端', '外场巡检'],
    faultSubcategoryList: [],
    organizationNameList: [],
    faultLocationList: [],
    faultLocationNameList: [],
    faultDescriptionValue: '',
    maintenanceRequirementList: ['修复', '新增', '拆除', '清除', '外场处理', '其他'],
    dispatchOpinionValue: '',
    isAccidentOptions: [{
        value: '是',
        text: '是'
      },
      {
        value: '否',
        text: '否'
      }
    ],
    isDispatchedOptions: [{
        value: '是',
        text: '是'
      },
      {
        value: '否',
        text: '否'
      }
    ],
    isDispatchedChangeValue: true,
    attachments: [],
    faultLocation: '',
    resultList: []
  },
  onLoad() {
    this.getFormRequiredList()
    this.form = new Form({
      initialValues: {},
      rules: {
        projectName: [{
          required: true,
          message: '请选择',
        }],
        contractName: [{
          required: true,
          message: '请选择',
        }],
        isAccident: [{
          required: true,
          message: '请选择',
        }],
        responseLevel: [{
          required: true,
          message: '请选择',
        }],
        responseTime: [{
          required: true,
          message: '请输入',
        }],
        faultCategory: [{
          required: true,
          message: '请选择',
        }],
        faultSubcategory: [{
          required: true,
          message: '请选择',
        }],
        organizationName: [{
          required: true,
          message: '请选择',
        }],
        faultLocation: [{
          required: true,
          message: '请选择',
        }],
        faultDescription: [{
          required: true,
          message: '请选择',
        }],
        isDispatched: [{
          required: true,
          message: '请选择',
        }],
        maintenanceRequirement: [{
          required: true,
          message: '请选择',
        }],
        dispatchOpinion: [{
          required: true,
          message: '请输入',
        }],
      },
    });
    // 直接new Form内初始化，会与Picker 组件冲突，可延迟 0 毫秒（放入事件队列末尾），等待组件渲染完成
    setTimeout(() => {
      this.form.setFieldsValue({
        isAccident: '否',
        responseLevel: '常规',
        responseTime: '24',
        isDispatched: '是'
      });
    }, 0);
  },
  onReady() {
    // this.mapCtx = dd.createMapContext('map');

    // console.log(this.mapCtx)
  },
  handleRef(ref) {
    this.form.addItem(ref);
  },
  getFormRequiredList() {
    api.getProjectName().then(res => {
      const projectNameList = []
      res.forEach(item => {
        projectNameList.push(item.projectName)
      });
      this.setData({
        projectNameList
      })
    })
    api.getSubcategoryTypeList().then(res => {
      const faultSubcategoryList = []
      const list = res.rows
      list.forEach(item => {
        faultSubcategoryList.push(item.typeName)
      })
      this.setData({
        faultSubcategoryList
      })
    })
    api.getOrganizationTypeList().then(res => {
      const organizationNameList = []
      const list = res.rows
      list.forEach(item => {
        organizationNameList.push(item.organizationName)
      })
      this.setData({
        organizationNameList
      })
    })
    api.getPointInfoList().then(res => {
      if (res.length === 0) return
      const faultLocationNameList = []
      res.forEach(item => {
        faultLocationNameList.push(item.pointName)
      })
      this.setData({
        faultLocationList: res,
        faultLocationNameList
      })
    })
  },
  search(kw) {
    if (!kw) {
      this.setData({
        resultList: []
      });
      return;
    }
    const {
      faultLocationList
    } = this.data
    const list = faultLocationList.filter(item =>
      item.pointName.includes(kw)
    );
    this.setData({
      resultList: list
    });
  },
  faultLocationControlledOk(val) {
    console.log(val)
    const kw = val.trim()
    if (this._timer) clearTimeout(this._timer)
    this._timer = setTimeout(() => {
      this.search(kw)
    }, 200)
  },
  resultClick(e) {
    const {
      id,
      pointName,
      longitude,
      latitude
    } = e.currentTarget.dataset.val
    if (pointName) {
      this.form.setFieldValue('faultLocation', pointName)
      this.setData({
        resultList: []
      })
    }
    if (latitude && longitude) {
      const markers = [{
        id,
        longitude,
        latitude,
        title: pointName,
        width: "20",
        height: "30",
        iconPath: "/images/mark_point.png",
      }]
      this.setData({
        markers,
        latitude,
        longitude
      })
      this.setData({
        locationFlag: true
      })
    } else {
      this.setData({
        locationFlag: false
      })
    }
  },
  projectNameControlledOk(value) {
    this.setData({
      projectNameValue: value,
    }, () => {
      this.getContractNamesList(value)
    });
  },
  isDispatchedChange(e) {
    this.setData({
      isDispatchedChangeValue: e === '是' ? e : null
    })
  },
  async submit() {
    const values = await this.form.submit();
    console.log(values);
    const faultLocationIsSelected = this.data.faultLocationNameList.find(item =>
      item === values.faultLocation
    )
    if (!faultLocationIsSelected) {
      my.showToast({
        content: '请选择故障地点',
        type: 'fail'
      })
      return
    }
    my.showLoading({
      content: '提交中'
    })

    const {
      attachments
    } = this.data
    const params = {
      ...values,
      organizationName: '',
      attachments
    }
    try {
      const res = await api.faultReport(params)
      console.log(res)
      my.hideLoading()
      if (res.code === 200) {
        my.showToast({
          content: res.msg,
          type: 'success',
          duration: 2000
        })
        my.navigateBack()
      } else {
        my.showToast({
          content: res.msg,
          type: 'fail',
          duration: 2000
        })
      }
    } catch (e) {
      my.hideLoading()
      console.error(`故障上报提交失败：${e}`)
      my.showToast({
        content: e || '提交失败',
        type: 'fail',
        duration: 2000
      })
    }
  },
  async getContractNamesList(projectName) {
    try {
      const res = await api.getContractNamesByProjectName({
        projectName
      })
      if (res.length === 0) return
      const contractNameList = []
      res.forEach(item => {
        contractNameList.push(item.contractName)
      })
      this.setData({
        contractNameList
      })
    } catch (e) {
      console.error(e)
    }
  },
  contractNameControlledOk(value) {
    this.setData({
      contractName: value
    }, () => {
      api.getIoCompany({
        name: value
      }).then(res => {
        if (res) {
          this.setData({
            ioCompany: res
          }, () => {
            this.form.setFieldValue('ioCompany', res)
          })
        }
      })
    })
  },
  imageRemove(e) {
    const fileNameFromPath = e.path.split('/').pop();
    // console.log(fileNameFromPath)
    const list = this.data.attachments
    const filteredList = list.filter(item => item.fileName !== fileNameFromPath);
    // console.log(filteredList)
    this.setData({
      attachments: filteredList
    })
  },
  imageBeforeUpload(localFileList) {

    console.log(localFileList)
    const {
      attachments
    } = this.data
    console.log(attachments)
    if (attachments.length === 0) {
      return new Promise(res => {
        res(localFileList[0])
      })
    } else {
      const {
        path
      } = localFileList[0]
      const waitingUploadPathName = path.split('/').pop()
      console.log(waitingUploadPathName)
      console.log(localFileList[0])
      if (waitingUploadPathName === attachments[0].fileName) {
        console.log('已存在')
        return false
      } else {
        return new Promise(res => {
          res(localFileList[0])
        })
      }

    }
  },
  async onUpload(localFile) {
    if (!localFile || !localFile.path) {
      console.error('上传失败：未获取到有效的图片临时路径');
      throw new Error('上传失败：未获取到有效的图片临时路径');
    }

    const tempFilePath = localFile.path;
    const res = await api.imageUpload(tempFilePath);
    if (!res) {
      console.error('上传失败：接口未返回有效的图片URL');
      throw new Error('上传失败：接口未返回有效的图片URL');
    }
    // console.log(res);
    const attachments = this.data.attachments
    attachments.push(res)
    this.setData({
      attachments
    })
    console.log(this.data.attachments)
    return tempFilePath;
  },
  imagePreview(file) {
    // console.log(file)
    const fileName = file.path.split('/').pop()
    const imageInfo = this.data.attachments.find(item => {
      return item.fileName === fileName
    })
    console.log(imageInfo.url)
    const {
      url
    } = imageInfo
    this.previewSingleImage(url)
  },
  previewSingleImage(url) {
    dd.previewImage({
      urls: [url],
      current: url,
      success: () => {
        console.log('图片预览成功');
      },
      fail: (err) => {
        console.error('图片预览失败', err);
        dd.showToast({
          content: '预览失败，请重试',
          type: 'fail',
          duration: 2000
        });
      }
    });
  },
  cancel() {
    my.navigateBack()
  },
  responseLevelConfirm(e) {
    console.log(e)
    if (e === '常规') {
      this.form.setFieldValue('responseTime', '24')
    }
  }
});